<template>
    <div class="service-form-container">
        <!-- 页面头部 -->
        <div class="page-header">
            <div class="header-content">
                <div class="header-left">
                    <h2>{{ isEdit ? '编辑服务' : '新增服务' }}</h2>
                </div>
                <div class="header-right">
                    <el-button @click="handleCancel">
                        <el-icon><ArrowLeft /></el-icon>
                        返回
                    </el-button>
                </div>
            </div>
        </div>

        <!-- 表单内容 -->
        <div class="form-content">
            <el-card shadow="never" class="form-card">
                <el-form
                    ref="serviceFormRef"
                    :model="formData"
                    :rules="formRules"
                    label-width="120px"
                    class="service-form"
                >
                    <!-- 服务代码 -->
                    <el-form-item label="服务代码:" prop="serviceCode">
                        <el-input
                            v-model="formData.serviceCode"
                            placeholder="输入服务代码"
                            style="width: 300px"
                        />
                    </el-form-item>

                    <!-- 服务名称 -->
                    <el-form-item label="服务名称:" prop="serviceName">
                        <el-input
                            v-model="formData.serviceName"
                            placeholder="输入服务名称"
                            style="width: 300px"
                        />
                    </el-form-item>

                    <!-- 服务种类 -->
                    <el-form-item label="服务种类:" prop="serviceType">
                        <el-select v-model="formData.serviceType" placeholder="请选择" style="width: 200px">
                            <el-option label="咨询" :value="1" />
                            <el-option label="预约服务" :value="2" />
                        </el-select>
                    </el-form-item>

                    <!-- 服务类型 -->
                    <el-form-item label="服务类型:" prop="serviceCategory">
                        <el-input
                            v-model="formData.serviceCategory"
                            placeholder="输入服务类型描述"
                            style="width: 300px"
                        />
                    </el-form-item>

                    <!-- 专家ID -->
                    <el-form-item label="专家ID:" prop="expertId">
                        <el-input
                            v-model="formData.expertId"
                            placeholder="输入专家ID"
                            style="width: 300px"
                        />
                    </el-form-item>

                    <!-- 专家名称 -->
                    <el-form-item label="专家名称:" prop="expertName">
                        <el-input
                            v-model="formData.expertName"
                            placeholder="输入专家名称"
                            style="width: 300px"
                        />
                    </el-form-item>

                    <!-- 服务价格 -->
                    <el-form-item label="服务价格:" prop="price">
                        <el-input
                            v-model="formData.price"
                            placeholder="输入服务价格"
                            style="width: 300px"
                        />
                    </el-form-item>

                    <!-- 上下架状态 -->
                    <el-form-item label="上下架状态:" prop="serviceStatus">
                        <el-radio-group v-model="formData.serviceStatus">
                            <el-radio :value="0">下架</el-radio>
                            <el-radio :value="1">上架</el-radio>
                        </el-radio-group>
                    </el-form-item>

                    <!-- 审批状态 -->
                    <el-form-item label="审批状态:" prop="approvalStatus">
                        <el-select v-model="formData.approvalStatus" placeholder="请选择" style="width: 200px">
                            <el-option label="待审批" :value="0" />
                            <el-option label="审批通过" :value="1" />
                            <el-option label="审批拒绝" :value="2" />
                            <el-option label="审批中" :value="3" />
                        </el-select>
                    </el-form-item>

                    <!-- 服务描述 -->
                    <el-form-item label="服务描述:" prop="description">
                        <el-input
                            v-model="formData.description"
                            type="textarea"
                            :rows="4"
                            placeholder="输入服务描述"
                            style="width: 500px"
                        />
                    </el-form-item>

                    <!-- 操作按钮 -->
                    <el-form-item>
                        <div class="form-actions">
                            <el-button @click="handleCancel">取消</el-button>
                            <el-button type="primary" @click="handleSubmit">发布</el-button>
                        </div>
                    </el-form-item>
                </el-form>
            </el-card>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { ArrowLeft } from '@element-plus/icons-vue';
import { createExpertService, updateExpertService, getExpertServiceDetail } from '@/api/product/expert-service';

const route = useRoute();
const router = useRouter();

const id = route.params.id as string;
const isEdit = computed(() => !!id);

// 表单引用
const serviceFormRef = ref();

// 表单数据
const formData = reactive({
    serviceCode: '',
    serviceName: '',
    serviceType: null,
    serviceCategory: '',
    expertId: '',
    expertName: '',
    price: '',
    serviceStatus: 1,
    approvalStatus: 0,
    description: '',
    sortOrderValue: ''
});

// 表单验证规则
const formRules = {
    serviceCode: [
        { required: true, message: '请输入服务代码', trigger: 'blur' },
        { min: 1, max: 50, message: '服务代码长度在1-50个字符', trigger: 'blur' }
    ],
    serviceName: [
        { required: true, message: '请输入服务名称', trigger: 'blur' },
        { min: 2, max: 50, message: '服务名称长度在2-50个字符', trigger: 'blur' }
    ],
    serviceType: [
        { required: true, message: '请选择服务种类', trigger: 'change' }
    ],
    serviceCategory: [
        { required: true, message: '请输入服务类型', trigger: 'blur' },
        { min: 2, max: 100, message: '服务类型长度在2-100个字符', trigger: 'blur' }
    ],
    expertId: [
        { required: true, message: '请输入专家ID', trigger: 'blur' },
        { min: 1, max: 50, message: '专家ID长度在1-50个字符', trigger: 'blur' }
    ],
    expertName: [
        { required: true, message: '请输入专家名称', trigger: 'blur' },
        { min: 2, max: 50, message: '专家名称长度在2-50个字符', trigger: 'blur' }
    ],
    price: [
        { required: true, message: '请输入服务价格', trigger: 'blur' },
        { pattern: /^\d+(\.\d{1,2})?$/, message: '请输入正确的价格格式', trigger: 'blur' }
    ],
    serviceStatus: [
        { required: true, message: '请选择上下架状态', trigger: 'change' }
    ],
    approvalStatus: [
        { required: true, message: '请选择审批状态', trigger: 'change' }
    ],
    description: [
        { max: 500, message: '服务描述长度不能超过500个字符', trigger: 'blur' }
    ],
    sortOrderValue: [
        { pattern: /^\d+$/, message: '请输入正整数', trigger: 'blur' }
    ]
};

// 提交表单
const handleSubmit = async () => {
    if (!serviceFormRef.value) return;
    
    try {
        await serviceFormRef.value.validate();
        
        // 构建提交数据
        const submitData = {
            serviceCode: formData.serviceCode,
            serviceName: formData.serviceName,
            serviceType: formData.serviceType,
            serviceCategory: formData.serviceCategory,
            expertId: formData.expertId,
            expertName: formData.expertName,
            price: parseFloat(formData.price),
            serviceStatus: formData.serviceStatus,
            approvalStatus: formData.approvalStatus,
            description: formData.description,
            sortOrderValue: formData.sortOrderValue ? parseInt(formData.sortOrderValue) : undefined
        };

        let res;
        if (isEdit.value) {
            // 编辑模式
            const updateData = { ...submitData, id: id };
            res = await updateExpertService(updateData);
        } else {
            // 新增模式
            res = await createExpertService(submitData);
        }

        const responseData = res as any;
        if (responseData && responseData.code === 200) {
            ElMessage.success(`${isEdit.value ? '更新' : '创建'}成功`);
            router.push('/service-list');
        } else {
            ElMessage.error((responseData && responseData.msg) || `${isEdit.value ? '更新' : '创建'}失败`);
        }
    } catch (error) {
        if (error !== false) {
            console.error('保存失败:', error);
            ElMessage.error('操作失败，请稍后重试');
        }
    }
};

// 取消操作
const handleCancel = () => {
    router.push('/service-list');
};

// 页面初始化
onMounted(() => {
    if (isEdit.value) {
        // 编辑模式：加载现有数据
        loadServiceData(id);
    }
});

// 加载服务数据
const loadServiceData = async (serviceId: string) => {
    try {
        const res = await getExpertServiceDetail(serviceId);
        const responseData = res as any;
        
        if (responseData && responseData.code === 200 && responseData.data) {
            const data = responseData.data;
            Object.assign(formData, {
                serviceCode: data.serviceCode || '',
                serviceName: data.serviceName || '',
                serviceType: data.serviceType || null,
                serviceCategory: data.serviceCategory || '',
                expertId: data.expertId || '',
                expertName: data.expertName || '',
                price: data.price ? data.price.toString() : '',
                serviceStatus: data.serviceStatus || 1,
                approvalStatus: data.approvalStatus || 0,
                description: data.description || '',
                sortOrderValue: data.sortOrderValue ? data.sortOrderValue.toString() : ''
            });
        } else {
            ElMessage.error('获取服务详情失败');
        }
    } catch (error) {
        console.error('加载服务数据失败:', error);
        ElMessage.error('网络错误，请稍后重试');
    }
};
</script>

<style scoped>
.service-form-container {
    padding: 20px;
    background-color: #f5f5f5;
    min-height: 100vh;
}

.page-header {
    border-radius: 8px;
    margin-bottom: 20px;
}

.header-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.header-left h2 {
    margin: 0;
    color: #333;
    font-size: 24px;
}

.form-content {
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.form-card {
    border-radius: 8px;
}

.service-form {
    padding: 30px;
}

.form-hint {
    color: #f56c6c;
    font-size: 12px;
    margin-top: 4px;
}

.form-actions {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
    margin-top: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .service-form-container {
        padding: 10px;
    }
    
    .header-content {
        flex-direction: column;
        gap: 16px;
        align-items: flex-start;
    }
    
    .service-form {
        padding: 20px;
    }
    
    .form-actions {
        justify-content: center;
    }
}
</style>
